import { acceptHMRUpdate, defineStore } from "pinia";
import type {KeyValue} from "~/types";

export const useTabsStore = defineStore("tabs", () => {
    const tabs=reactive<{[key:string]:any}>({});
    const coms=reactive<{[key:string]:any}>({});
    const addTagList=reactive({});
    const setTabs=(key:string,value:any)=>tabs[key]=value
    const getTabs=(key:string)=>tabs[key]
    const setComs=(key:string,value:any)=>coms[key]=value
    const getComs=(key:string)=>coms[key]
    const active=reactive({})
    const setActive=(key:string,value:number)=>active[key]=value
    const getActive=(key:string)=>active[key]
    const modifyTag=(key:string,index,tag:string)=>{

        if(index>-1&&index<tabs[key].length){
            tabs[key][index]=tag??tabs[key][index].tag;
        }
    }
    const addTag=(key:string,obj:{tag:string,component:any},index?:number)=>{
        if(index===undefined){
            tabs[key].push(obj.tag);
            coms[key].push(obj.component);
        }else{
            tabs[key].splice(index,0,obj.tag);
            tabs[key].splice(index,0,obj.component);
        }
        const tmp={...obj,before:active[key]}
        addTagList[key]=addTagList[key]?.length?addTagList[key].push(tmp):[tmp];
        active[key]=index===undefined?tabs[key].length-1:index;
    }
    const removeTag=(key:string,tag:string)=>{
        const index=tabs[key].findIndex((item:string)=>item==tag);
        if(index>-1){
            tabs[key].splice(index,1);
            coms[key].splice(index,1);
        }
        const ind=addTagList[key].findIndex((item:any)=>item.tag==tag);
        if(ind>-1){
            const current=addTagList[key][ind];
            addTagList[key].splice(index,1);
            active[key]=current.before||0
        }
    }
    return {
        tabs,
        coms,
        addTagList,
        setTabs,
        getTabs,
        setComs,
        getComs,
        active,
        setActive,
        getActive,
        addTag,
        removeTag,
        modifyTag
    }
});

if (import.meta.hot){
    import.meta.hot.accept(acceptHMRUpdate(useTabsStore, import.meta.hot));
}